<template>
  <div>
    <div class="card">
      <div v-if="data.table.no">
        <div style="display: flex">
          <div style="flex: 1">
            餐桌号： {{ data.table.no }}
          </div>
          <el-button type="primary" @click="startOrder" v-if="!data.orderFlag">开始点餐</el-button>
          <el-button type="primary" @click="checkOut">结账</el-button>
          <el-button type="primary" @click="removeOrder">退桌</el-button>
        </div>
      </div>
      <div style="color: #666;" v-else>
        <div style="display: flex">
        <div style="flex: 1">
          您还未选餐桌，请先选择合适的餐桌再点餐
        </div>
        <el-button type="primary" @click="selectTable" >选择餐桌</el-button>
        </div>
      </div>
    </div>
      <!--       展示餐品-->
      <el-card class="box-card" style="margin-top: 10px;" v-if="data.table.no">
        <div slot="header">
          <span>我的订单</span>
        </div>
        <el-table :data="data.selectedFoodsData">
          <el-table-column prop="id" label="序号" width="70"/>
          <el-table-column prop="name" label="名称"/>
          <el-table-column prop="descr" label="简介"/>
          <el-table-column prop="price" label="价格"/>
          <el-table-column label="图片">
            <template v-slot="scope">
              <el-image style="width: 100px; height: 100px; display: block" v-if="scope.row.img" :src="scope.row.img"
                        :preview-src-list="[scope.row.img]" preview-teleported></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="num" label="数量"/>
        </el-table>
      </el-card>

    <div class="modal">
      <el-dialog v-model="data.orderVisible" title="餐品信息" show-overflow-tooltip width="80%"
                 destory-on-close>
        <el-table :data="data.tableData" style="height: 500px">
          <el-table-column prop="id" label="序号" width="70"/>
          <el-table-column prop="name" label="名称"/>
          <el-table-column prop="descr" label="简介"/>
          <el-table-column prop="price" label="价格"/>
          <el-table-column label="图片">
            <template v-slot="scope">
              <el-image style="width: 100px; height: 100px; display: block" v-if="scope.row.img" :src="scope.row.img"
                        :preview-src-list="[scope.row.img]" preview-teleported></el-image>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <!--              <el-button type="primary" @click="order(scope.row)">点餐</el-button>-->
              <el-input-number @change="(e)=>handleChange(e,scope.row)" :initValue="0" :min="0"
                               label="描述文字"></el-input-number>
            </template>
          </el-table-column>
        </el-table>
        <div style="height: 30px">
<!--          <el-pagination style="float: left" background layout="prev, pager, next" @current-change="loadFoods"-->
<!--                         :page-size="data.pageSize"-->
<!--                         v-model:current-page="data.pageNum" :total="data.total"/>-->
          <div style="float: right;margin-bottom: 5px">
            <span>餐品：{{ data.selectedFoodsTotal }}件</span>
            <span style="margin: 0 10px 0 10px">共计：{{ data.selectedFoodsPriceTotal }}</span>
            <el-button type="primary" @click="order" :disabled="data.selectedFoodsTotal ==0">
              点餐
            </el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import {reactive} from "vue";

import request from "@/utils/request";
import router from "../../router";
import {ElMessage, ElMessageBox} from "element-plus";

const data = reactive({
  tableData: [],
  selectedFoodsData: [],
  total: 0,
  pageNum: 1,  // 当前的页码
  pageSize: 5,  // 每页的个数
  formVisible: false,
  orderVisible: false,
  table: {},
  user: JSON.parse(localStorage.getItem('canteen-user') || '{}'),
  orderData: [],//选中的餐品信息
  orderInfo: {},//订单信息
  selectedFoods: [],//选中的餐品信息
  selectedFoodsTotal: 0,//选中餐品件数合计
  selectedFoodsPriceTotal: 0,//选中餐品价格合计
  orderFlag: false,//是否点餐成功
});

const selectTable = () => {
  router.push('/home')
}


const order = async () => {
  try {
    // 发起支付并生成订单的请求
    const res = await request.post('/order/updateOrder', {
      tableId: data.table.id,
      tableNo: data.table.no,
      userId: data.user.id,
      id: data.orderInfo.id,
      foodNum: data.selectedFoodsTotal,
      totalPrice: data.selectedFoodsPriceTotal
    });
    if (res.code === 200) {
      // 添加明细成功，批量插入明细
      batchInsertDetail(res.data.id);
      // 重新加载表格数据
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    ElMessage.error("请求出错：" + error.message);
  }
};


// 批量插入明细函数
const batchInsertDetail = (orderId) => {
  // 处理选中餐品的数据
  data.selectedFoods.map(item => {
    item.foodId = item.id
    delete item.id; // 删除原本的 id 属性
    return item;
  })
  // 发起批量插入明细的请求
  request.post('/order/batchInsertDetail', {
    selectedFoods: JSON.stringify(data.selectedFoods),
    userId: data.user.id,
    orderId: orderId
  }).then(res => {
    if (res.code === 200) {  //成功
      data.orderVisible = false
      loadCurrentSelectFoods(orderId)// 加载当前选中的食物
      data.orderFlag = true
      ElMessage.success('点餐成功')
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 加载当前点选的餐品数据
const loadCurrentSelectFoods = (orderId) =>{
  request.post('/orderDetail/queryAll', {
    orderId: orderId
  }).then(res => {
    if (res.code === 200) {  //成功
      data.selectedFoodsData = res.data
    } else {
      ElMessage.error(res.msg)
    }
  })
}
// 初始化选中的餐品信息
const initValue = () => {
  // 清空选中的餐品数组及其相关总计
  data.selectedFoods = []
  data.selectedFoodsTotal = 0
  data.selectedFoodsPriceTotal = 0
}
// 处理选中餐品的数量变化
const handleChange = (value, row) => {
  // 如果已选中该餐品，更新数量
  if (data.selectedFoods.includes(row)) {
    row.num = value
    // 如果未选中，添加到选中数组并设置数量为1
  } else {
    row.num = 1
    data.selectedFoods.push(row)
  }
  // 重新计算总数量和总价格
  let selectedFoodsTotal = 0
  let selectedFoodsPriceTotal = 0
  data.selectedFoods.map(item => {
    selectedFoodsTotal += item.num
    selectedFoodsPriceTotal += (item.price * item.num)
  })
  data.selectedFoodsTotal = selectedFoodsTotal
  data.selectedFoodsPriceTotal = selectedFoodsPriceTotal
}
// 加载餐品数据的函数
const loadFoods = () => {
  request.post('/foods/selectFoodList', {
    name: data.name
  }).then(res => {
    // 更新表格数据
    data.tableData = res.data || []
  })
}

// const selectedFoodsData = () => {
//   request.get('/foods/selectedFoodsData', {
//     params: {
//       pageNum: data.pageNum,
//       pageSize: data.pageSize,
//       name: data.name
//     }
//   }).then(res => {
//     data.tableData = res.data?.list || []
//     data.total = res.data.total
//   })


const loadTable = () => {
  // 根据用户ID获取餐桌信息
  request.get('/tables/selectByUserId' + '?userId=' + data.user.id).then(res => {
    // 设置获取到的桌台信息
    data.table = res.data || {}
    if(JSON.stringify(data.table)!='{}'){ // 如果餐桌信息不为空
      // 获取用户最新正在进行的订单信息
      request.post('/order/getUserNewestOrder',{userId:data.user.id}).then(res => {
        data.orderInfo = res.data// 设置获取到的订单信息
        loadCurrentSelectFoods(data.orderInfo.id)  // 加载当前选定的食物信息
      })
    }
  })
}
loadTable()

const startOrder = () => {
  initValue()  // 初始化数据
  data.orderVisible = true
  loadFoods()
}
// 定义结账函数
const checkOut = () => {
  request.post('/order/checkOut', data.orderInfo).then(res => {
    if (res.code === 200) {
      // 获取服务器返回的数据
      const val1 = res.data
      ElMessageBox.confirm('总计：'+ val1.totalPrice + "元", '确认支付', { type: 'warning' }).then(res => {
        // 设置支付成功后的订单状态
        const val2 = {}
        val2.id = data.orderInfo.id
        val2.state = '2'   // 设置支付成功后的订单状态
        // 更新订单状态为已支付
        request.post('/order/updateOrder', val2).then(res => {
          if (res.code === 200) {
            ElMessage.success('结账成功')
            //退桌
            request.put('/tables/removeOrder', data.table).then(res => {
              data.table = {}// 清空本地餐桌数据
            })
          } else {
            ElMessage.error(res.msg)
          }
        })
      })
    } else {
      ElMessage.error(res.msg)
    }
  })
}



const removeOrder = () => {
  ElMessageBox.confirm('您确认要退桌吗？', '确认', { type: 'warning' }).then(res => {
    request.put('/tables/removeOrder', data.table).then(res => {
      if (res.code === 200) {
        ElMessage.success('退桌成功')
        data.table = {}
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}

</script>

<style scoped>
.clearfix:after {
  clear: both
}
</style>
